//
//  RHDeviceListFilterVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/3/11.
//

#import "RHDeviceListFilterVC.h"
#import "RHDeviceListCell.h"
#import "RHDeviceStatusVC.h"
#import "RHDeviceModel.h"
#import <MGSwipeTableCell.h>
#import "RHDeviceBindVC.h"
#import "RHSearchView.h"
#import "RHAlertView.h"
#import "RHDeviceFilterView.h"

@interface RHDeviceListFilterVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic ,copy) NSString *keyCode;

@property (nonatomic, strong) RHSearchView *searchView;

@property (nonatomic, strong) RHDeviceFilterView *filterView;//筛选
@end

@implementation RHDeviceListFilterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _deviceListArr = [NSMutableArray array];
    [self.view setBackgroundColor:CFTabViewBgColor];
    self.currentPage = 1;
    self.numOfPage = 10;
    self.requestType = RequestTypeRefresh;
    [self setupUI];
    [self getDeviceList];
    
}
-(void)setDeviceListArr:(NSMutableArray *)deviceListArr
{
    _deviceListArr = deviceListArr;
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)setupUI{
    kWeakSelf;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deviceCountDidChange) name:DeviceListNeedUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getDeviceList) name:UserModifyDeviceName object:nil];
    
    UIView *topView = kView;
    topView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(0);
        make.height.offset(45);
    }];
    //搜索栏
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    
    _searchView.isAutoHideSearchButton = NO;
    [topView addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入关键字".rh_localized;
   
    
    QMUIButton *filterBtn = [QMUIButton buttonWithImage:@"device_filter"];
    [filterBtn addTarget:self action:@selector(deviceFilterAction) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:filterBtn];
    [filterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(35);
        make.right.mas_offset(-5);
        make.top.equalTo(weakSelf.searchView);
    }];
    
    [_searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_offset(0);
        make.right.equalTo(filterBtn.mas_left).offset(10);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHDeviceListCell class] forCellReuseIdentifier:@"RHDeviceListCell"];
    [_tableView registerClass:[RHDeviceListCell class] forCellReuseIdentifier:@"RHDeviceListCell_noPlantName"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.equalTo(topView.mas_bottom);
    }];
   
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        weakSelf.keyCode = @"";
        [weakSelf getDeviceList];
        if(weakSelf.refreshBlock){
            weakSelf.refreshBlock();
        }
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getDeviceList];
    }];
}
#pragma mark ------- action ----------

-(void)searchDeviceWithKeyCode:(NSString*)keyCode
{
    self.currentPage = 1;
    self.requestType = RequestTypeRefresh;
    [self.tableView endFooterResetNoMoreData];
    self.keyCode = keyCode;
    [self getDeviceList];
}

//自己添加设备成功后
-(void)updateDeviceList
{
    [self searchDeviceWithKeyCode:self.keyCode];
}

//分发设备成功
-(void)deviceCountDidChange
{
    [self getDeviceList];
    if(self.refreshBlock){
        self.refreshBlock();
    }
}

//添加设备  设备分发成功后更新列表
-(void)getDeviceList
{
    [self getDeviceListOfUser];
}

#pragma mark ---- 筛选
-(void)deviceFilterAction
{
    if (_filterView == nil) {
        kWeakSelf;
        _filterView = [[RHDeviceFilterView alloc]initWithType:1];
        _filterView.filterBlock = ^(NSDictionary * _Nonnull filterDic) {
            weakSelf.filterDic = filterDic;
            [weakSelf searchDeviceWithKeyCode:@""];
        };
    }
    _filterView.filterDic = self.filterDic;
    [_filterView showInWindowAnimate];
    
}

#pragma mark ----- 获取用户设备列表 ------
-(void)getDeviceListOfUser
{
   
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{
                           @"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"deviceStatus":ValidNullData(self.filterDic[@"deviceStatus"]),
                           @"runningStatus":ValidNullData(self.filterDic[@"runStatus"]),
                           @"deviceType":ValidNullData(self.filterDic[@"deviceType"]),
                           @"deviceId":ValidNullData(self.keyCode)
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_getDeviceListByFilter argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        [self.tableView endFooterRefresh];
        if(resultModel.code == 200){
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                self.deviceListArr = arr;
            }else{//上拉加载
                [self.deviceListArr addObjectsFromArray:arr];
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshCustomWithNoMoreData];
            }
            [self.tableView reloadData];
           
            if(self.deviceListArr.count == 0){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           [self.tableView endHeaderRefresh];
           [self.tableView endFooterRefresh];
    }];
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.deviceListArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceListCell *cell;
    cell = [tableView dequeueReusableCellWithIdentifier:@"RHDeviceListCell"];
    cell.listType = DevListTypeAll;
    RHDeviceModel *device = self.deviceListArr[indexPath.row];
    cell.device = device;

    kWeakSelf;
    cell.modifyBlock = ^() {
        [weakSelf modifyDeviceNameAction:device];
    };

    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceModel *device = self.deviceListArr[indexPath.row];
 
    if(device.lastOnlineTime == 0){
        [QMUITips showError:@"请让设备先连接云平台".rh_localized];
        return;
    }
    RHDeviceStatusVC *vc = [[RHDeviceStatusVC alloc] init];
    vc.deviceModel = device;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ------- textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.keyCode = textField.text;
    [self getDeviceList];
    [self.searchView resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.keyCode = @"";
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getDeviceList];
        [self.searchView resignFirstResponder];
    });
    return YES;
}

-(void)modifyDeviceNameAction:(RHDeviceModel*)devModel
{
    kWeakSelf;
    RHAlertView *alertView = [[RHAlertView alloc]initWithType:RHAlertTypeTextView title:@"修改设备名称".rh_localized subTitle:nil];
    [alertView setDefaultText:devModel.deviceName];
    alertView.sureBlock = ^(NSString * _Nonnull content) {
        [weakSelf modifyDeviceName:content deviceId:devModel.deviceId];
    };
    [alertView show];
}

#pragma mark ----- 修改设备名
-(void)modifyDeviceName:(NSString*)devName deviceId:(NSString*)deviceId
{
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startPutWithCompletionAPIKey:H_modifyDeviceName argument:@{@"deviceId":deviceId,@"deviceName":devName} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"成功".rh_localized];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //通知其他列表更新
                [kNotificationCenter postNotificationName:UserModifyDeviceName object:nil];
            });
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
